package com.example.demo.service.impl;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import com.example.demo.service.ImageGenerationService;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.*;

/**
 * 图片生成服务实现类
 * 基于通义千问文生图API实现角色头像自动生成
 */
@Slf4j
public class ImageGenerationServiceImpl implements ImageGenerationService {

    private final String apiKey;
    private final String baseUrl;
    
    public ImageGenerationServiceImpl(String apiKey, String baseUrl) {
        this.apiKey = apiKey;
        this.baseUrl = baseUrl;
    }

    static {
        // 设置API基础URL
        Constants.baseHttpApiUrl = "https://dashscope.aliyuncs.com/api/v1";
    }

    @Override
    public String generateRoleAvatar(String roleDescription) {
        return generateRoleAvatar(null, roleDescription);
    }

    @Override
    public String generateRoleAvatar(String roleName, String roleDescription) {
        try {
            log.info("开始生成角色头像，角色名：{}，描述：{}", roleName, roleDescription);
            
            // 构建图片生成提示词
            String prompt = buildImagePrompt(roleName, roleDescription);
            log.info("生成的提示词：{}", prompt);
            
            // 调用通义千问文生图API
            String imageUrl = callQwenImageAPI(prompt);
            
            if (imageUrl != null) {
                log.info("角色头像生成成功，图片URL：{}", imageUrl);
                return imageUrl;
            } else {
                log.error("角色头像生成失败，返回URL为空");
                return null;
            }
            
        } catch (Exception e) {
            log.error("生成角色头像时发生异常", e);
            return null;
        }
    }

    /**
     * 构建图片生成提示词
     */
    private String buildImagePrompt(String roleName, String roleDescription) {
        StringBuilder promptBuilder = new StringBuilder();
        
        // 基础提示词
        promptBuilder.append("请生成一个高质量的角色头像，风格为现代插画或动漫风格。");
        
        // 添加角色名称（如果有）
        if (roleName != null && !roleName.trim().isEmpty()) {
            promptBuilder.append("角色名称：").append(roleName).append("。");
        }
        
        // 添加角色描述
        if (roleDescription != null && !roleDescription.trim().isEmpty()) {
            promptBuilder.append("角色特征：").append(roleDescription).append("。");
        }
        
        // 添加画质和风格要求
        promptBuilder.append("要求：高清晰度，精美细节，适合作为头像使用，背景简洁，突出人物特征。");
        promptBuilder.append("画面构图：头像特写或半身像，居中构图。");
        promptBuilder.append("色彩风格：色彩丰富但不过于鲜艳，整体和谐统一。");
        
        return promptBuilder.toString();
    }

    /**
     * 调用通义千问文生图API
     */
    private String callQwenImageAPI(String prompt) throws ApiException, NoApiKeyException, UploadFileException, IOException {
        // 检查API Key
        String actualApiKey = apiKey;
        if (actualApiKey == null || actualApiKey.trim().isEmpty()) {
            actualApiKey = System.getenv("DASHSCOPE_API_KEY");
        }
        
        if (actualApiKey == null || actualApiKey.trim().isEmpty()) {
            log.error("未配置DASHSCOPE_API_KEY，无法生成图片");
            return null;
        }

        MultiModalConversation conv = new MultiModalConversation();

        // 构建用户消息
        MultiModalMessage userMessage = MultiModalMessage.builder()
                .role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("text", prompt)
                ))
                .build();

        // 设置参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("watermark", false); // 不添加水印
        parameters.put("prompt_extend", true); // 启用提示词扩展
        parameters.put("negative_prompt", "低质量,模糊,变形,多余的手指,多余的肢体,不协调的比例"); // 负面提示词
        parameters.put("size", "1328*1328"); // 图片尺寸

        // 构建请求参数
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(actualApiKey)
                .model("qwen-image-plus") // 使用qwen-image-plus模型
                .messages(Collections.singletonList(userMessage))
                .parameters(parameters)
                .build();

        // 调用API
        MultiModalConversationResult result = conv.call(param);
        
        // 解析结果
        if (result != null && result.getOutput() != null && 
            result.getOutput().getChoices() != null && 
            !result.getOutput().getChoices().isEmpty()) {
            
            var choice = result.getOutput().getChoices().get(0);
            if (choice.getMessage() != null && choice.getMessage().getContent() != null) {
                var content = choice.getMessage().getContent();
                for (var item : content) {
                    if (item instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> contentMap = (Map<String, Object>) item;
                        if (contentMap.containsKey("image")) {
                            return contentMap.get("image").toString();
                        }
                    }
                }
            }
        }
        
        log.error("API调用成功但未能解析出图片URL，响应：{}", JsonUtils.toJson(result));
        return null;
    }
}